#!/usr/bin/env node
import { existsSync, readFileSync } from 'fs'
import { resolve } from 'path'
import { spawn } from 'child_process'

function loadSigningEnv() {
  const explicitlyNoSign = process.env.CSC_IDENTITY_AUTO_DISCOVERY === 'false'
  if (explicitlyNoSign) {
    return
  }

  const keys = [
    'WIN_CSC_LINK',
    'WIN_CSC_KEY_PASSWORD',
    'CSC_LINK',
    'CSC_KEY_PASSWORD',
  ]

  const missing = keys.filter((k) => !process.env[k] || process.env[k] === '')
  if (missing.length === 0) return

  const localConfigPath = resolve('scripts', 'signing.local.json')
  const examplePath = resolve('scripts', 'signing-config.example.json')
  const cfgPath = existsSync(localConfigPath) ? localConfigPath : (existsSync(examplePath) ? examplePath : null)
  if (!cfgPath) return

  try {
    const cfg = JSON.parse(readFileSync(cfgPath, 'utf-8'))
    for (const k of keys) {
      if (!process.env[k] && cfg[k]) {
        process.env[k] = String(cfg[k])
      }
    }
  } catch (e) {
    console.warn('[signing] Failed to load signing config:', e.message)
  }
}

function ensureMirrors() {
  if (!process.env.ELECTRON_BUILDER_NO_GH_PROXY) {
    process.env.ELECTRON_BUILDER_NO_GH_PROXY = 'true'
  }
}

function run() {
  loadSigningEnv()
  ensureMirrors()

  const args = process.argv.slice(2)
  // Build web first
  const build = spawn(process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm', ['run', 'build'], { stdio: 'inherit', env: process.env })
  build.on('exit', (code) => {
    if (code !== 0) process.exit(code ?? 1)
    const ebArgs = [...args]
    const eb = spawn(process.platform === 'win32' ? 'electron-builder.cmd' : 'electron-builder', ebArgs, { stdio: 'inherit', env: process.env })
    eb.on('exit', (c) => process.exit(c ?? 0))
  })
}

run()


